package com.xyhuo.leetcode.january;

/**
 * 两数之和Ⅱ -输入有序数组
 * https://leetcode.cn/problems/two-sum-ii-input-array-is-sorted/
 *
 * @time 2024/1/29
 */
public class TwoSum {

//    public static void main(String[] args) {
//        TwoSum ts = new TwoSum();
//        int[] nums = {2, 7, 11, 15};
//        ts.twoSum(nums, 9);
//    }

    public int[] twoSum(int[] numbers, int target) {
        int[] ans = new int[2];
        for (int i = 0; i < numbers.length; i++) {
            int findTarget = find(numbers, i + 1, numbers.length-1, target - numbers[i]);
            if (findTarget != -1) {
                ans[0] = i + 1;
                ans[1] = findTarget + 1;
                return ans;
            }
        }
        return ans;
    }

    private int find(int[] nums, int left, int right, int target) {
        while (left <= right) {
            int middle = (right - left) / 2 + left;
            if (nums[middle] == target) {
                return middle;
            } else if (nums[middle] < target) {
                left = middle + 1;
            } else if (nums[middle] > target) {
                right = middle - 1;
            }
        }
        return -1;
    }
}
